﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using DAL;
using Common;

namespace BLL
{
    /// <summary>
    /// 
    /// </summary>
    public class SysMenuBLL : BaseBLL
    {
        /// <summary>
        /// 
        /// </summary>
        SysMenuRepository repository = null;
        public SysMenuBLL()
        {
            repository = new SysMenuRepository();
        }
        public FlexigridObject FlexigridList(string id, FlexigridParam param)
        {


            int page = param.Page.GetInt();
            int rp = param.RP.GetInt();

            using (SysEntities db = new SysEntities())
            {
                IQueryable<SysMenu> queryData = repository.DaoChuData(db, param);
                int count = queryData.Count();
                if (count > 0)
                {
                    queryData = queryData.Skip((page - 1) * rp).Take(rp);

                    foreach (var item in queryData)
                    {
                        if (param.Cols.Contains("ParentId"))
                        {
                            if (item.ParentId != null && item.ParentId.Length == 36 && item.SysMenu2 != null)
                            {
                                item.ParentId = item.SysMenu2.Name;//可以做成超链接
                            }
                        }

                        if (param.Cols.Contains("SysWebSiteId"))
                        {
                            if (item.SysWebSiteId != null && item.SysWebSiteId.Length == 36 && item.SysWebSite != null)
                            {
                                item.SysWebSiteId = item.SysWebSite.Name;//可以做成超链接
                            }
                        }

                        if (param.Cols.Contains("SysRoleId") && item.SysRole != null)
                        {
                            item.SysRoleId = string.Empty;
                            foreach (var it in item.SysRole)
                            {
                                item.SysRoleId += it.Name + ' ';
                            }
                        }

                    }

                }
                FlexigridObject flexigridObject = new FlexigridObject()
                {
                    FlexigridPara = param,
                    total = (count > 0) ? count : 0,
                    Query = queryData
                };
                return flexigridObject;
            }
        }
        /// <summary>
        /// 在查询中输入字符串，自动提示的功能
        /// </summary>
        /// <param name="id">需要查询的数据库字段的名称</param>
        /// <param name="term">输入的字符串</param>
        /// <returns></returns>  
        public string SearchAutoComplete(string id, string term)
        {
            FlexigridParam param = new FlexigridParam();
            param.Query = id + "&" + term + "^";
            param.SortName = id;

            List<string> listString = new List<string>();
            using (SysEntities db = new SysEntities())
            {
                var queryData = repository.DaoChuData(db, param);
                if (queryData != null)
                {
                    queryData = queryData.Take(5).Distinct();
                    foreach (var item in queryData)
                    {
                        listString.Add(FlexigridRow.GetPropertyList(item, new string[] { id }).FirstOrDefault());
                    }
                }
            }

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("[");
            int i = 0;
            foreach (var item in listString)
            {
                if (string.IsNullOrEmpty(item))
                {
                    continue;
                }
                if (i == 0)
                {
                    i++;
                    stringBuilder.Append(@"{@label@:@" + item + "@}");
                }
                else
                {
                    stringBuilder.Append(",");
                    stringBuilder.Append(@"{@label@:@" + item + "@}");
                }
            }
            stringBuilder.Append("]");
            return stringBuilder.ToString().Replace('@', '"') ;
        }
        public bool DeleteCollection(ref ValidationErrors validationErrors, string[] deleteCollection)
        {
            if (deleteCollection != null)
            {
                if (deleteCollection.Length == 1)
                {
                    return this.Delete(ref validationErrors, deleteCollection[0]);
                }
                else if (deleteCollection.Length > 1)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        using (SysEntities db = new SysEntities())
                        {
                            repository.Delete(db, deleteCollection);
                            if (deleteCollection.Length == repository.Save(db))
                            {
                                transactionScope.Complete();
                                return true;
                            }
                            else
                            {
                                Transaction.Current.Rollback();
                            }
                        }
                    }
                }
            }
            return false;
        }
        public bool Delete(ref ValidationErrors validationErrors, string id)
        {
            return repository.Delete(id) == 1;
        }
        public bool CreateCollection(ref ValidationErrors validationErrors, IQueryable<SysMenu> entitys)
        {
            if (entitys != null)
            {
                int flag = 0, count = entitys.Count();
                if (count > 0)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        using (SysEntities db = new SysEntities())
                        {
                            foreach (var entity in entitys)
                            {
                                if (Create(ref validationErrors, db, entity))
                                {
                                    flag++;
                                }
                                else
                                {
                                    Transaction.Current.Rollback();
                                    return false;
                                }
                            }
                            if (count == flag)
                            {
                                transactionScope.Complete();
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
       public bool Create(ref ValidationErrors validationErrors, SysEntities db, SysMenu entity)
        {   
            int count = 1;
        
            foreach (var item in entity.SysRoleId.GetIdSort())
            {
                SysRole sys = new SysRole { Id = item };
                db.SysRole.Attach(sys);
                entity.SysRole.Add(sys);
                count++;
            }

            repository.Create(db, entity);
            if (count == repository.Save(db))
            {
                return true;
            }
            else
            {
                validationErrors.Add("创建出错了");
            }
            return false;
        }
        public bool Create(ref ValidationErrors validationErrors, SysMenu entity)
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                using (SysEntities db = new SysEntities())
                {
                    if (Create(ref validationErrors, db, entity))
                    {
                        transactionScope.Complete();
                        return true;
                    }
                    else
                    {
                        Transaction.Current.Rollback();
                    }
                }
            }
            return false;
        }

        public bool EditCollection(ref ValidationErrors validationErrors, IQueryable<SysMenu> entitys)
        {
            if (entitys != null)
            {
                int flag = 0, count = entitys.Count();
                if (count > 0)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        using (SysEntities db = new SysEntities())
                        {
                            foreach (var entity in entitys)
                            {
                                if (Edit(ref validationErrors, db, entity))
                                {
                                    flag++;
                                }
                                else
                                {
                                    Transaction.Current.Rollback();
                                    return false;
                                }
                            }
                            if (count == flag)
                            {
                                transactionScope.Complete();
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }

       public bool Edit(ref ValidationErrors validationErrors, SysEntities db, SysMenu entity)
        {  /*                       
                           * 不操作 原有 现有
                           * 增加   原没 现有
                           * 删除   原有 现没
                           */
            if (entity == null)
            {
                return false;
            }
            int count = 1;
            SysMenu editEntity = repository.Edit(db, entity);
            
            List<string> addSysRoleId = new List<string>();
            List<string> deleteSysRoleId = new List<string>();
            GetDiffrent(entity.SysRoleId.GetIdSort(), entity.SysRoleIdOld.GetIdSort(), ref addSysRoleId, ref deleteSysRoleId);
            if (addSysRoleId != null && addSysRoleId.Count() > 0)
            {
                foreach (string item in addSysRoleId)
                {
                    SysRole sys = new SysRole { Id = item };
                    db.SysRole.Attach(sys);
                    editEntity.SysRole.Add(sys);
                    count++;
                }
            }
            if (deleteSysRoleId != null && deleteSysRoleId.Count() > 0)
            {
                List<SysRole> listEntity = new List<SysRole>();
                foreach (string item in deleteSysRoleId)
                {
                    SysRole sys = new SysRole { Id = item };
                    listEntity.Add(sys);
                    db.SysRole.Attach(sys);
                }
                foreach (SysRole item in listEntity)
                {
                    editEntity.SysRole.Remove(item);//查询数据库
                    count++;
                }
            } 

            if (count == repository.Save(db))
            {
                return true;
            }
            else
            {
                validationErrors.Add("编辑出错了");
            }
            return false;
        }
        public bool Edit(ref ValidationErrors validationErrors, SysMenu entity)
        {
            using (TransactionScope transactionScope = new TransactionScope())
            {
                using (SysEntities db = new SysEntities())
                {
                    if (Edit(ref validationErrors, db, entity))
                    {
                        transactionScope.Complete();
                        return true;
                    }
                    else
                    {
                        Transaction.Current.Rollback();
                    }
                }
            }
            return false;
        }
        public List<SysMenu> GetAll()
        {
            SysEntities db = new SysEntities();            
            return repository.GetAll(db).ToList();          
        }     
        
        public List<SysMenuSef> GetAllMetadata()
        {
            SysEntities db = new SysEntities();
            return repository.GetAll(db).Select(s =>
                new SysMenuSef
                {
                   Id = s.Id
					,Name = s.Name
					,_parentId = s.ParentId
					,SysWebSiteId =  (s.SysWebSiteId == null) ? string.Empty : s.SysWebSite.Name
					,Url = s.Url
					,Iconic = s.Iconic
					,Sort = s.Sort
					,State = s.State
					
                }).OrderBy(o => o.Sort).ToList();
        }
            
        public SysMenu GetById(string id)
        {
            SysEntities db = new SysEntities();            
            return repository.GetById(db, id);           
        }
        
        /// <summary>
        /// 获取在该表一条数据中，出现的所有外键实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>外键实体集合</returns>
        public List<SysRole> GetRefSysRole(string id)
        {
            using (SysEntities db = new SysEntities())
            {
                return repository.GetRefSysRole(db, id).ToList();
            }
        }
        /// <summary>
        /// 获取在该表中出现的所有外键实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>外键实体集合</returns>
        public List<SysRole> GetRefSysRole()
        {
            using (SysEntities db = new SysEntities())
            {
                return repository.GetRefSysRole(db).ToList();
            }
        }

    }
}

